// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.dashboard.ui.map

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.Group
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.coroutines.launch
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.departures.DeparturesActivity
import xyz.apiote.bimba.czwek.repo.Locatable
import xyz.apiote.bimba.czwek.repo.OnlineRepository
import xyz.apiote.bimba.czwek.repo.Position
import xyz.apiote.bimba.czwek.repo.Stop
import xyz.apiote.bimba.czwek.repo.TrafficResponseException
import xyz.apiote.bimba.czwek.repo.Vehicle

class MapViewModel : ViewModel() {

	private val _locatables = MutableLiveData<List<Locatable>>()
	val locatables: MutableLiveData<List<Locatable>> = _locatables

	fun getLocatablesIn(cm: ConnectivityManager, bl: Position, tr: Position, context: Context) {
		viewModelScope.launch {
			viewModelScope.launch {
				try {
					val repository = OnlineRepository()
					_locatables.value = repository.getLocatablesIn(cm, bl, tr, context) ?: emptyList()
				} catch (e: TrafficResponseException) {
					Log.w("Map", "$e")
				}
			}
		}
	}
}

class MapBottomSheet(private val locatable: Locatable) : BottomSheetDialogFragment() {
	companion object {
		const val TAG = "MapBottomSheet"
	}

	private fun showVehicle(content: View, vehicle: Vehicle) {
		content.findViewById<Group>(R.id.stop_group).visibility = View.GONE
		content.findViewById<Group>(R.id.vehicle_group).visibility = View.VISIBLE

		context?.let { ctx ->
			content.findViewById<TextView>(R.id.title).apply {
				text = ctx.getString(R.string.vehicle_headsign, vehicle.Line.name, vehicle.Headsign)
				contentDescription = ctx.getString(
					R.string.vehicle_headsign_content_description,
					vehicle.Line.name,
					vehicle.Headsign
				)
			}
			// todo units -- [3.2] settings or system-based
			content.findViewById<TextView>(R.id.speed_text).text =
				ctx.getString(R.string.speed_in_km_per_h, vehicle.Speed * 3.6)
			content.findViewById<TextView>(R.id.congestion_text).text = vehicle.congestion(ctx)
			content.findViewById<TextView>(R.id.occupancy_text).text = vehicle.occupancy(ctx)
			content.findViewById<ImageView>(R.id.ac).visibility =
				if (vehicle.getCapability(Vehicle.Capability.AC)) {
					View.VISIBLE
				} else {
					View.GONE
				}
			content.findViewById<ImageView>(R.id.bike).visibility =
				if (vehicle.getCapability(Vehicle.Capability.BIKE)) {
					View.VISIBLE
				} else {
					View.GONE
				}
			content.findViewById<ImageView>(R.id.voice).visibility =
				if (vehicle.getCapability(Vehicle.Capability.VOICE)) {
					View.VISIBLE
				} else {
					View.GONE
				}
			content.findViewById<ImageView>(R.id.ticket).visibility =
				if (vehicle.let {
						it.getCapability(Vehicle.Capability.TICKET_DRIVER) || it.getCapability(Vehicle.Capability.TICKET_MACHINE)
					}) {
					View.VISIBLE
				} else {
					View.GONE
				}
			content.findViewById<ImageView>(R.id.usb).visibility =
				if (vehicle.getCapability(Vehicle.Capability.USB_CHARGING)) {
					View.VISIBLE
				} else {
					View.GONE
				}
		}
	}

	private fun showStop(content: View, stop: Stop) {
		context?.let { ctx ->
			content.findViewById<Group>(R.id.stop_group).visibility = View.VISIBLE
			content.findViewById<Group>(R.id.vehicle_group).visibility = View.GONE
			content.findViewById<TextView>(R.id.title).text = stop.name
			content.findViewById<Button>(R.id.departures_button).setOnClickListener {
				val intent = Intent(ctx, DeparturesActivity::class.java).apply {
					putExtra("code", stop.code)
					putExtra("name", stop.name)
					putExtra("feedID", stop.feedID)
				}
				startActivity(intent)
			}
			content.findViewById<Button>(R.id.navigation_button).setOnClickListener {
				try {
					startActivity(
						Intent(
							Intent.ACTION_VIEW,
							Uri.parse("geo:${stop.location().latitude},${stop.location().longitude}")
						)
					)
				} catch (_: ActivityNotFoundException) {
					Toast.makeText(context, ctx.getString(R.string.no_map_app), Toast.LENGTH_SHORT).show()
				}
			}

			stop.changeOptions(ctx).let { changeOptions ->
				content.findViewById<TextView>(R.id.change_options).apply {
					text = changeOptions.first
					contentDescription = changeOptions.second
				}
			}
		}
	}


	override fun onCreateView(
		inflater: LayoutInflater,
		container: ViewGroup?,
		savedInstanceState: Bundle?
	): View {
		val content = inflater.inflate(R.layout.map_bottom_sheet, container, false)
		content.apply {
			when (locatable) {
				is Vehicle -> {
					showVehicle(this, locatable)
				}

				is Stop -> {
					showStop(this, locatable)
				}
			}
		}
		//(dialog as BottomSheetDialog).behavior.peekHeight = dpToPixelI(90f)

		return content
	}
}